<template>
  <div class="modern-home" v-if="refresh" :key="refresh">
    <front-header></front-header>
    
    <div class="main-content">
      <!-- 轮播图 -->
      <div class="hero-section">
        <front-carousel></front-carousel>
      </div>
      
      <!-- 快速导航卡片 -->
      <div class="quick-nav">
        <div class="container">
          <div class="quick-nav-grid">
            <div 
              v-for="(item, index) in quickNavItems" 
              :key="index" 
              class="quick-nav-item"
              @click="$router.push(item.path)"
            >
              <div class="quick-nav-icon">
                <i :class="item.icon"></i>
              </div>
              <span class="quick-nav-text">{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分类区域 -->
      <div class="category-section">
        <div class="container">
          <front-category></front-category>
        </div>
      </div>

      <!-- 精选产品区域 -->
      <div class="featured-products">
        <div class="container">
          <div class="section-header">
            <h2 class="section-title">精选农产品</h2>
            <div class="section-line"></div>
            <div class="view-all" @click="$router.push('/products')">
              查看全部 <i class="el-icon-arrow-right"></i>
            </div>
          </div>
          
          <div class="products-grid">
            <div 
              v-for="(product, index) in recommendProducts" 
              :key="product.id"
              class="product-grid-item"
              :class="{'featured': index === 0}"
            >
              <product-card :product="product" @add-to-cart="handleAddToCart" @add-to-favorite="handleToggleFavorite"></product-card>
            </div>
          </div>
        </div>
      </div>

      <!-- 新品上市区域 -->
      <div class="new-products-section">
        <div class="container">
          <div class="section-header">
            <h2 class="section-title">新品上市</h2>
            <div class="section-line"></div>
            <div class="view-all" @click="$router.push('/products?tag=new')">
              查看全部 <i class="el-icon-arrow-right"></i>
            </div>
          </div>
          
          <div class="innovation-grid">
            <div 
              v-for="product in newProducts" 
              :key="product.id"
              class="innovation-item"
            >
              <product-card :product="product" @add-to-cart="handleAddToCart" @add-to-favorite="handleToggleFavorite"></product-card>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 服务特点区域 -->
      <div class="features-section">
        <div class="container">
          <div class="section-header center">
            <h2 class="section-title">我们的服务特点</h2>
            <div class="section-line"></div>
          </div>
          
          <div class="features-grid">
            <div class="feature-item">
              <div class="feature-icon">
                <i class="el-icon-data-analysis"></i>
              </div>
              <h3>数据驱动</h3>
              <p>利用大数据分析优化农业生产流程，提高产量和质量</p>
            </div>
            
            <div class="feature-item">
              <div class="feature-icon">
                <i class="el-icon-cpu"></i>
              </div>
              <h3>智能科技</h3>
              <p>应用人工智能和物联网技术，实现农业生产的智能化管理</p>
            </div>
            
            <div class="feature-item">
              <div class="feature-icon">
                <i class="el-icon-money"></i>
              </div>
              <h3>金融支持</h3>
              <p>提供灵活的融资方案，助力农业企业和农户发展壮大</p>
            </div>
            
            <div class="feature-item">
              <div class="feature-icon">
                <i class="el-icon-s-cooperation"></i>
              </div>
              <h3>专家咨询</h3>
              <p>连接农业专家资源，提供专业技术指导和解决方案</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <front-footer></front-footer>
  </div>
</template>

<script>
import FrontHeader from '@/components/front/FrontHeader.vue'
import FrontFooter from '@/components/front/FrontFooter.vue'
import FrontCarousel from '@/components/front/FrontCarousel.vue'
import FrontCategory from '@/components/front/FrontCategory.vue'
import ProductCard from '@/components/front/ProductCard.vue'
import Request from '@/utils/request'

export default {
  name: 'Home',
  components: {
    FrontHeader,
    FrontFooter,
    FrontCarousel,
    FrontCategory,
    ProductCard
  },
  data() {
    return {
      recommendProducts: [],
      newProducts: [],
      isLoggedIn: false,
      refresh: true,
      quickNavItems: [
        { label: '科技产品', icon: 'el-icon-s-goods', path: '/products' },
        { label: '专家咨询', icon: 'el-icon-s-custom', path: '/experts' },
        { label: '技术知识库', icon: 'el-icon-notebook-2', path: '/front/knowledge' },
        { label: '融资服务', icon: 'el-icon-money', path: '/finance-manager' }
      ]
    }
  },
  methods: {
    // 修改 checkLoginStatus 方法
    checkLoginStatus() {
      const token = localStorage.getItem('token');
      const userStr = localStorage.getItem('frontUser');
      
      if (token && userStr) {
        try {
          const user = JSON.parse(userStr);
       
          // 检查用户角色，如果不是 USER 则注销
          if (user.role !== 'USER') {
            this.logout();
            this.$message.warning('请使用普通用户账号访问');
            return;
          }
          this.isLoggedIn = true;
        } catch (error) {
          this.logout();
        }
      } else {
        this.isLoggedIn = false;
      }
    },

    // 修改 logout 方法
    logout() {
      localStorage.removeItem('token');
      localStorage.removeItem('frontUser');
      this.isLoggedIn = false;
      // 强制刷新整个页面
      window.location.reload()
    },

    // 获取推荐商品
    async getRecommendProducts() {
      try {
        // 重新检查登录状态
        this.checkLoginStatus();
        
        let products = [];
        
        if (!this.isLoggedIn) {
          // 未登录状态 - 获取随机排序的前8条商品
          const res = await Request.get('/product/page?status=1&size=8');
          if (res.code === '0') {
            products = res.data.records || res.data;
            // 随机排序
            products = products.sort(() => Math.random() - 0.5);
          }
        } else {
          // 登录状态 - 获取个性化推荐
          const userStr = localStorage.getItem('frontUser');
          if (!userStr) {
            throw new Error('User info not found');
          }
          const userId = JSON.parse(userStr).id;
          const res = await Request.get('/product/page?status=1&size=8');
          //const res = await Request.get(`/recommend/user/${userId}`);
          if (res.code === '0') {
            products = res.data.records || res.data;
          }
          
          // 获取收藏状态
          try {
            const favRes = await Request.get(`/favorite/user/${userId}`);
            if (favRes.code === '0') {
              const favorites = favRes.data;
              products = products.map(product => ({
                ...product,
                isFavorite: favorites.some(f => f.productId === product.id && f.status === 1)
              }));
            }
          } catch (error) {
            console.error('获取收藏状态失败:', error);
            products = products.map(product => ({
              ...product,
              isFavorite: false
            }));
          }
        }

        // 设置推荐商品
        this.recommendProducts = products.map(product => ({
          ...product,
          isFavorite: product.isFavorite || false
        }));

      } catch (error) {
        console.error('获取推荐商品失败:', error);
        // 如果获取失败，回退到未登录状态的推荐
        this.isLoggedIn = false;
        this.getRecommendProducts();
      }
    },
    // 获取新品
    async getNewProducts() {
      try {
        const res = await Request.get('/product/page?status=1&sort=updatedAt,desc&size=4')
        if (res.code === '0') {
          this.newProducts = res.data.records.map(product => ({
            ...product,
            isFavorite: false
          }))
        }
      } catch (error) {
        console.error('获取新品失败:', error)
      }
    },
    // 添加到购物车
    handleAddToCart(product) {
      this.$message({
        type: 'success',
        message: '已添加到购物车'
      })
    },
    // 切换收藏状态
    async handleToggleFavorite({ product, status }) {
      // 更新本地数据
      const targetProduct = this.recommendProducts.find(p => p.id === product.id)
      if (targetProduct) {
        targetProduct.isFavorite = status === 1
      }
      
      // 重新获取推荐商品列表
      await this.getRecommendProducts()
    }
  },
  created() {
    // 添加登录状态检查
    this.checkLoginStatus();
    this.getRecommendProducts();
    this.getNewProducts();
  },
  mounted() {
    const userStr = localStorage.getItem('frontUser');
    if (userStr) {
      this.isLoggedIn = true;
    }
  }
}
</script>

<style scoped>
.modern-home {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f9f9f9;
  color: #333;
}

.main-content {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  width: 100%;
  box-sizing: border-box;
}

/* 英雄区域 */
.hero-section {
  width: 100%;
  margin-bottom: 40px;
}

/* 快速导航区域 */
.quick-nav {
  margin: 40px 0 60px;
}

.quick-nav-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.quick-nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 16px;
  background: #fff;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
  text-align: center;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
}

.quick-nav-item:hover {
  transform: translateY(-5px);
  background: #fff;
  border-color: #4caf50;
  box-shadow: 0 10px 25px rgba(76, 175, 80, 0.15);
}

.quick-nav-icon {
  width: 70px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: linear-gradient(135deg, #4caf50, #81c784);
  margin-bottom: 16px;
  color: #fff;
  font-size: 30px;
  box-shadow: 0 5px 15px rgba(76, 175, 80, 0.2);
}

.quick-nav-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

/* 分类区域 */
.category-section {
  margin-bottom: 60px;
}

/* 公共区域样式 */
.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  position: relative;
}

.section-header.center {
  justify-content: center;
  text-align: center;
  flex-direction: column;
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
  letter-spacing: 0.5px;
}

.section-line {
  height: 3px;
  width: 60px;
  background: linear-gradient(90deg, #4caf50, #81c784);
  border-radius: 3px;
  margin-left: 20px;
}

.section-header.center .section-line {
  margin-left: 0;
  margin-top: 15px;
}

.view-all {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4caf50;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.view-all:hover {
  color: #388e3c;
  transform: translateX(5px);
}

/* 精选产品区域 */
.featured-products {
  margin-bottom: 60px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 25px;
}

.product-grid-item.featured {
  grid-column: span 2;
  grid-row: span 2;
}

/* 新品上市区域 */
.new-products-section {
  margin-bottom: 60px;
}

.innovation-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 25px;
}

/* 服务特点区域 */
.features-section {
  padding: 60px 0;
  background: #fff;
  margin-bottom: 60px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.05);
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30px;
  margin-top: 40px;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 30px 20px;
  background: #fff;
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
}

.feature-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(76, 175, 80, 0.15);
  border-color: #4caf50;
}

.feature-icon {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: linear-gradient(135deg, #4caf50, #81c784);
  margin-bottom: 20px;
  color: #fff;
  font-size: 32px;
  box-shadow: 0 5px 15px rgba(76, 175, 80, 0.2);
}

.feature-item h3 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 15px;
}

.feature-item p {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .products-grid,
  .innovation-grid,
  .features-grid {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .product-grid-item.featured {
    grid-column: span 1;
    grid-row: span 1;
  }
}

@media (max-width: 992px) {
  .quick-nav-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .products-grid,
  .innovation-grid,
  .features-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .section-line {
    margin-left: 0;
    margin-top: 10px;
  }
  
  .view-all {
    margin-left: 0;
    margin-top: 15px;
  }
  
  .features-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 576px) {
  .quick-nav-grid,
  .products-grid,
  .innovation-grid {
    grid-template-columns: 1fr;
  }
  
  .quick-nav-item {
    padding: 20px 16px;
  }
  
  .quick-nav-icon {
    width: 60px;
    height: 60px;
    font-size: 26px;
  }
  
  .section-title {
    font-size: 24px;
  }
}
</style> 